<!-- 测评题库管理 -->

<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>测评题库</el-breadcrumb-item>
      <el-breadcrumb-item>测评题库管理</el-breadcrumb-item>
    </el-breadcrumb>
    <hr />

    <!-- 头部搜索栏 -->
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="题目">
          <el-select
            v-model="formInline.title"
            placeholder="请选择题目"
            clearable
            @clear="handleClear3()"
          >
            <el-option
              v-for="option in nameList"
              :key="option.titleId"
              :label="option.title"
              :value="option.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getData">搜索</el-button>
          <el-button type="success" @click="dialogFormVisible = true">新增测评题库</el-button>
          <el-button type="danger" @click="delIds()">批量删除</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增测评题库 -->

      <el-dialog v-model="dialogFormVisible" title="新增测评题库" width="730px">
        <el-form :model="form">
          <el-form-item label="题目名" :label-width="formLabelWidth">
            <el-input
              v-model="form.title"
              placeholder="请输入题目名"
              :rules="[{ required: true }]"
              style="width: 90%"
            />
          </el-form-item>
          <!-- 下拉选项测评名称 -->
          <el-form-item label="测评名称" :label-width="formLabelWidth">
            <el-select
              v-model="form.psychologyTestId"
              placeholder="请选择测评分类"
              clearable
              filterable
              style="width: 90%"
            >
              <el-option
                v-for="item in psychologyTestList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="题目选项"
            :label-width="formLabelWidth"
            :rules="[{ required: true }]"
          >
            <div class="options-grid" style="width: 90%">
              <div v-for="(option, index) in form.options" :key="index" class="option-item">
                {{ String.fromCharCode(65 + index) }}.
                <el-input v-model="option.content" placeholder="请输入选项内容" />
                <el-button type="danger" @click="form.options.splice(index, 1)">删除</el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button
              type="primary"
              @click="form.options.length < 4 && form.options.push({ content: '' })"
              :disabled="form.options.length >= 4"
            >
              添加选项（{{ form.options.length }}/4）
            </el-button>
            <el-button @click="addNo()">取消</el-button>
            <el-button type="primary" @click="addYes()">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 查看对话框 -->
      <el-dialog v-model="dialogSelVisible" title="题目详情" width="730px">
        <el-form>
          <el-form-item label="题目ID" :label-width="formLabelWidth">
            <el-input v-model="viewData.id" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="题目名称" :label-width="formLabelWidth">
            <el-input v-model="viewData.title" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="测评名称" :label-width="formLabelWidth">
            <el-input v-model="viewData.psychologyTest.title" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="选项详情" :label-width="formLabelWidth">
            <div class="options-grid" style="width: 90%">
              <div v-for="(option, index) in viewData.options" :key="index" class="option-item">
                <span class="option-content">
                  {{ String.fromCharCode(65 + index) }}. {{ option.content }}</span
                >
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="dialogSelVisible = false" type="primary">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 编辑 -->
      <el-dialog v-model="edit" title="编辑题目" width="730px">
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="分类名称" :label-width="formLabelWidth">
            <el-input v-model="editForm.title" style="width: 90%" />
          </el-form-item>
          <el-form-item label="测评题目" :label-width="formLabelWidth">
            <el-select
              v-model="editForm.psychologyTestId"
              placeholder="请选择测评题目"
              clearable
              filterable
              style="width: 90%"
            >
              <el-option
                v-for="item in psychologyTestList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选项详情" :label-width="formLabelWidth">
            <div class="options-grid" style="width: 90%">
              <div v-for="(option, index) in editForm.options" :key="index" class="option-item">
                <el-input
                  v-model="option.content"
                  :placeholder="`${String.fromCharCode(65 + index)}选项内容`"
                />
                <el-button type="danger" @click="editForm.options.splice(index, 1)">删除</el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button
              type="primary"
              @click="editForm.options.length < 4 && editForm.options.push({ content: '' })"
              :disabled="editForm.options.length >= 4"
            >
              添加选项（{{ editForm.options.length }}/4）
            </el-button>
            <el-button @click="editNo">取消</el-button>
            <el-button type="primary" @click="editYes">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 表格数据展示 -->
    <div>
      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 95%; margin-left: 30px"
      >
        <el-table-column :selectable="selectable" type="selection" width="55" />
        <el-table-column label="ID" width="80">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column property="title" label="题目名称" />
        <el-table-column property="psychologyTest.title" label="测评名称" />
        <el-table-column label="选项">
          <template #default="scope">
            <div class="options-grid">
              <div v-for="(option, index) in scope.row.options" :key="index" class="option-item">
                <span class="option-content">
                  {{ String.fromCharCode(65 + index) }}.
                  {{ option.content }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="warning" size="small" @click="selYes(scope.row)"> 查看 </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页设置 -->
    <div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Test from '../test.vue'
// evaluation/page?evaluationName=&evaluationIntro=&pageNum=1&pageSize=10&classifyName=

// 设置表单元素接收数据
const formInline = reactive({
  title: '',
})
const nameList = reactive([{}])

// 设置表格接收数据
const tableData = reactive([])

// 页面挂载后加载数据
onMounted(() => {
  getData(), getClass(), getTestTitle()
})

// 清除输入框自动搜索
const handleClear1 = () => {
  formInline.evaluationName = ''
  getData()
}
const handleClear2 = () => {
  formInline.evaluationIntro = ''
  getData()
}
const handleClear3 = () => {
  formInline.title = ''
  getData()
}
//查看
const dialogSelVisible = ref(false)
const viewData = reactive({})
// 在methods部分添加查看方法
const selYes = (row) => {
  Object.assign(viewData, row)
  dialogSelVisible.value = true
  console.log(viewData)
}

// 接收新增数据
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  title: '',
  testId: '',
  options: [{ content: '' }],
})
// 新增测评分类列表数据源
const psychologyTestList = reactive([])
// 获取所有题目名
const getTestTitle = () => {
  axios.get('psychologyTest/findAllIdAndTitle').then((resp) => {
    console.log(resp.data)
    psychologyTestList.splice(0, psychologyTestList.length, ...resp.data)
  })
}
// 修改addNo方法
const addNo = () => {
  dialogFormVisible.value = false
  form.title = ''
  form.options = [{ content: '' }]
  ElMessage('取消添加')
}
// 更新addYes方法
const addYes = () => {
  if (form.options.length < 1 || form.options.length > 4) {
    ElMessage.error('请维护1-4个选项')
    return
  }
  if (!form.title?.trim()) {
    ElMessage.error('分类名称不能为空')
    return
  }
  if (!form.options.some((opt) => opt.content?.trim())) {
    ElMessage.error('选项内容不能为空')
    return
  }
  axios
    .post('psychologyTestTitle/addDuo', {
      title: form.title,
      testId: form.psychologyTestId,
      options: form.options,
    })
    .then((resp) => {
      if (resp.code == 200) {
        ElMessage({
          message: resp.message,
          type: 'success',
        })
        dialogFormVisible.value = false
        getData()
        form.title = ''
        form.options = [{ content: '' }]
      } else {
        ElMessage.error(resp.message)
      }
    })
}

const handleViewOption = (questionId, optionId) => {
  console.log('查看选项', questionId, optionId)
}

const handleEditOption = (questionId, optionId) => {
  console.log('修改选项', questionId, optionId)
}

// 编辑与删除
const edit = ref(false)
const editForm = reactive({})
const handleEdit = (index, row) => {
  axios.get(`psychologyTestTitle/findByIdDuo/${row.id}`).then((resp) => {
    Object.assign(editForm, {
      ...resp.data,
      psychologyTestId: resp.data.psychologyTest?.id, // 设置当前选中的测评ID
    })
    edit.value = true
  })
}
const editNo = () => {
  edit.value = false
  ElMessage('取消编辑')
  Object.assign(editForm, {
    title: '',
    options: [],
  })
}
const editYes = () => {
  axios
    .put('psychologyTestTitle/editDuo', { ...editForm, testId: editForm.psychologyTestId })
    .then((resp) => {
      if (resp.code == 200) {
        ElMessage({
          message: resp.message,
          type: 'success',
        })
      } else {
        ElMessage.error(resp.message)
      }
    })
    .catch((error) => {
      console.error('Error:', error)
      ElMessage.error('请求失败，请稍后再试')
    })
    .finally(() => {
      edit.value = false
      getData()
    })
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete(`psychologyTestTitle/del/${row.id}`)
        .then((resp) => {
          if (resp.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error(resp.message)
          }
        })
        .catch((error) => {
          console.error('Error:', error)
          ElMessage.error('请求失败，请稍后再试')
        })
        .finally(() => {
          getData()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除
const multipleSelection = ref([])
const ids = ref('')
const delIds = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请选择要删除的数据！')
  } else {
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续??', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ids.value = multipleSelection.value.map((row) => row.id).join(',')
        console.log(ids.value)
        axios
          .delete(`psychologyTestTitle/delBatch?ids=${ids.value}`)
          .then((resp) => {
            console.log(resp)
            if (resp.code == 200) {
              ElMessage({
                type: 'success',
                message: resp.message,
              })
            } else {
              ElMessage.error(resp.message)
            }
          })
          .catch((error) => {
            console.error('Error:', error)
            ElMessage.error('请求失败，请稍后再试')
          })
          .finally(() => {
            getData()
          })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 设置分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  getData()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  getData()
}

// 获取axios对象实例发送请求
const axios = getCurrentInstance().appContext.config.globalProperties.axios
// 获取表单数据
const getData = () => {
  axios
    .get(
      `psychologyTestTitle/findByCondition?pageNum=${currentPage.value}&pageSize=${pageSize.value}&title=${formInline.title}`
    )
    .then((resp) => {
      total.value = resp.data.total
      console.log(resp.data)
      tableData.splice(0, tableData.length, ...resp.data.list)
      console.log(resp.data.list)
    })
}
// 获取所有题目名
const getClass = () => {
  axios.get('psychologyTestTitle/findAllTitle').then((resp) => {
    console.log(resp.data)
    nameList.splice(0, nameList.length, ...resp.data)
  })
}
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 图片显示 */
.block {
  /* border: 1px solid #ccc; */
  width: 100px;
  height: 100px;
  background-color: rgb(245, 247, 250);
  text-align: center;
  line-height: 100px;
}

/* 文件上传 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 5px;
  margin-right: 5px;
}
button {
  padding: 16px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  background-color: rgb(251, 253, 255);
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
  border: 1px dashed rgb(192, 204, 218);
  border-radius: 5px;
}
.options-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 4px;
}
.option-label {
  color: #666;
  margin-right: 8px;
}
.option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  border-radius: 4px;
  // border: 1px solid #666;
  div {
    width: 100%;
    //表格边框边消失
    border: 0;
    input {
      width: 100%;
      padding: 4px 80px;
      margin-right: 5px;
    }
  }
  button {
    width: 20%;
    //按钮边框消失
    border: 0;
    margin-left: 5px;
  }
}
</style>